//问题模块
define('problem', ['config', 'cookie', 'jquery', 'handlebars', 'showBigImg'], function(config, cookie, $, Handlebars, showBigImg){
	//定义hanlebars helper
	function helper(){
		//判断当前用户是否已对该问题点赞
		Handlebars.registerHelper('if_zan', function(value, options){
			if(value == 1){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
		//判断头像是否为空
		Handlebars.registerHelper('if_empty', function(value, options){
			if(value == ''){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
		//判断回答是老师还是画室
		Handlebars.registerHelper('if_studio', function(value, options){
			if(value == 2){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
		//判断content是回答内容还是追问
		Handlebars.registerHelper('if_answer_content', function(value, options){
			if(value == 2 || value == 1){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
	}

	//处理服务器返回问题列表数据
	function process_data(data){
		//添加hasImage标记+处理时间戳
		for (var i = 0; i < data['problems'].length; i++) {
			if (data['problems'][i]['image'] != ''){
				data['problems'][i]['hasImage'] = true;
			}

			var publishTime = process_timestamp(data['problems'][i]['timestamp']);
			data['problems'][i]['publishTime'] = publishTime;
		}
		return data;
	}

	//时间戳处理
	function process_timestamp(data){
		var exp = new Date();
		exp.setTime(data);
		//把时间分开装入数组，对只有一位的值进行前补0处理
		var timeArray = [exp.getFullYear(), (exp.getMonth()+1), 
			exp.getDate(), exp.getHours(), exp.getMinutes(), exp.getSeconds()];
		for (var j = 0; j < 6; j++) {
			if (timeArray[j].toString().length == 1){
				timeArray[j] = '0' + timeArray[j];
			}
		}
		var publishTime = timeArray[0] + '.' + timeArray[1] + '.' + timeArray[2]
				+ '  ' + timeArray[3] + ':' + timeArray[4] + ':' + timeArray[5];

		return publishTime;
	}


	//返回函数列表
	return {
		//首页获取问题列表
		getProblemList: function(skip, total, userId, callback){
			var request = $.ajax({
				url: config['api']['getProblemList'][0],
				type: config['api']['getProblemList'][1],
				data: {
					skip: skip,
					total: total,
					userId: userId
				},
				dataType: 'json',
				async: true,
				error: function(err){
					console.log('get problem failed!');
				},
				success: function(data){
					//处理数据(添加publishTime, hasImage)
					data = process_data(data);
					console.log(data);
					//注册helper
					helper();
					//模板生成中心问题
					var source = $("#problems-template").html();
					var template = Handlebars.compile(source);
					$('.center-problem').html($('.center-problem').html() + template(data));

					//点开大图模块
					$('.articles .paintings img').on('click', function(){
						var src = $(this).attr('src');
						showBigImg(src);
					});


					//调用回调
					if (callback){
						callback(data['problems'].length);
					}
				}
			});
		},
		//详情页获取单一问题
		getProblemById: function(userId, problemId){
			//获取中心问题内容
			var problem_request = $.ajax({
				url: config['api']['getProblemById'][0].replace('<problem_id>', problemId),
				type: config['api']['getProblemById'][1],
				data: {
					userId: userId
				},
				dataType: 'json',
				async: true,
				error: function(err){
					console.log('get problem failed!');
				},
				success: function(data){
					//处理数据(添加publishTime, hasImage)
					if (data['problem']['image'] != ''){
						data['problem']['hasImage'] = true;
					}
					var publishTime = process_timestamp(data['problem']['timestamp']);
					data['problem']['publishTime'] = publishTime;

					//处理评论数据
					for (var i = 0; i < data['problem']['commentList'].length; i++) {
						publishTime = process_timestamp(data['problem']['commentList'][i]['timestamp']);
						data['problem']['commentList'][i]['publishTime'] = publishTime;
					}
					//处理回答数据
					for (var i = 0; i < data['problem']['answerList'].length; i++) {
						var updateTime_changed = process_timestamp(data['problem']['answerList'][i]['updateTime']);
						data['problem']['answerList'][i]['updateTime_changed'] = updateTime_changed;
					}				

					console.log(data);
					//注册helper
					helper();
					//模板生成中心问题
					var source = $("#problems-template").html();
					var template = Handlebars.compile(source);
					$('.center-problem').html($('.center-problem').html() + template(data['problem']));

					//点开大图模块
					$('.articles .paintings img').on('click', function(){
						var src = $(this).attr('src');
						showBigImg(src);
					});


					//模板生成问题评论
					if (data['problem']['commentList'].length > 0){		//评论数大于0
						source = $("#comments-template").html();
						template = Handlebars.compile(source);
						$('.main-comments').html($('.main-comments').html() + template(data['problem']['commentList']));

					}
					else{	//暂无评论
						$('.information h2').css('display', 'block');
					}

					//模板生成问题回答 + 判断是否显示追问框
					if (data['problem']['answerList'].length > 0){		//评论数大于0
						source = $("#answers-template").html();
						template = Handlebars.compile(source);
						$('.main-answers').html($('.main-answers').html() + template(data['problem']['answerList']));


						//隐藏或显示回答框(登录用户与提问用户相同)
						var fromUser = $('.articles').attr('data-userid');
						if (userId && userId == fromUser){
							$('.answer-container .reply').css('display', 'block');
						}
					}
					else{	//暂无回答
						$('.main-answers>h2').css('display', 'block');
					}

					//是老师，显示提问框，再判断回答列表是否有本老师回答
					if (cookie.getCookie('isTeacher') == 1){
						$('.main-answers .teacher-new-answer').css('display', 'block');

						var teacherId = cookie.getCookie('userId');
						for (var i = 0; i < data['problem']['answerList'].length; i++) {
							//该问题为本老师回答
							if (data['problem']['answerList'][i]['userId'] == teacherId){
								var $answer = $('.answer-container:eq(' + i + ') .reply');
								$answer.css('display','block');
								$answer.find('button').text('回复');
								$answer.find('input').attr('placeholder', '回复追问');
							}
						}
					}
				}
			});
		},
		//对问题点赞或取消赞
		clickZan: function(){
			$(document).on('click', '.center-problem .left-zan img', function(){
				var userId = cookie.getCookie('userId');
				if (userId != ''){		//已登录
					if ($(this).hasClass('active')){	//取消赞
						var zan = -1;
						$(this).removeClass('active');
						$(this).attr('src', 'image/clickZan.png');
						var $zan = $(this).parents('.left-zan').find('.num');
						var new_zan = parseInt($zan.text()) - 1;
						$zan.text(new_zan);
					}
					else{								//点赞
						var zan = 1;
						$(this).addClass('active');
						$(this).attr('src', 'image/clickZan_active.png');
						var $zan = $(this).parents('.left-zan').find('.num');
						var new_zan = parseInt($zan.text()) + 1;
						$zan.text(new_zan);
					}
					var problem_id = $(this).parents('.articles').attr('data-problemId');

					var request = $.ajax({
						url: config['api']['clickZan'][0].replace('<problem_id>', problem_id),
						type: config['api']['clickZan'][1],
						data: {
							userId: userId,
							zan: zan
						},
						dataType: 'json',
						async: true,
						err: function(err){
							console.log(err);
						}
					});
				}
				else{		//未登录
					//还原右上角登录图标
					$('#top_bar .user').css('display', 'none');
					$('#top_bar .log_reg').css('display', 'inline');
					//取消已点赞的显示
					$('.left-zan img').attr('src', 'image/clickZan.png').removeClass('active');
					$('.answer-container .reply').css('display', 'none');
					$('.main-answers .teacher-new-answer').css('display', 'none');
					alert('请先登录！');
				}
			});
		},
		//切换评论与回答
		clickAnswer_Comment: function(){
			//点击回答
			$(document).on('click', '.problem-comment .medium-answer', function(){
				$('.show-comments .main-comments').css('display', 'none');
				$('.show-comments .information').css('display', 'none');
				$('.show-comments .main-answers').css('display', 'block');
				$('.show-comments .bottom-triangle').css('left', '49%');
			});

			//点击评论
			$(document).on('click', '.problem-comment .right-comment', function(){
				$('.show-comments .main-comments').css('display', 'block');
				$('.show-comments .information').css('display', 'block');
				$('.show-comments .main-answers').css('display', 'none');
				$('.show-comments .bottom-triangle').css('left', '82%');
			});
		},
		//发布新回答
		newAnswer: function(){
			// var isTeacher = cookie.getCookie('isTeacher');
			// if (isTeacher == 1){
			// 	$('.main-answers .teacher-new-answer').css('display', 'block');
			// }

			$(document).on('click', '.main-answers .teacher-new-answer button', function(){

				var userId = cookie.getCookie('userId');
				if (userId != ''){
					var content = $(this).parent().find('input').val();
					var problemId = $(this).parents('.articles').attr('data-problemId');
					if (content == ''){
						alert('内容不能为空！');
						return ;
					}
					//改变按钮为不可选状态
					$(this).addClass('disabled');

					var request = $.ajax({
						url: config['api']['postAnswer'][0].replace('<user_id>', userId),
						type: config['api']['postAnswer'][1],
						data: {
							content: content,
							problemId: problemId
						},
						dataType: 'json',
						async: true,
						error: function(err){
							console.log('answer failed!');
							alert('回答失败，请重试！')
							$('.main-answers .teacher-new-answer button').removeClass('disabled');
						},
						success: function(data){
							alert('回答成功！');
							window.location.reload();
						}
					});
				}
				else{
					alert('请先登录！');
					$('#top_bar .user').css('display', 'none');
					$('#top_bar .log_reg').css('display', 'inline');	
					$('.user-info').css('display', 'none');
					$('.answer-container .reply').css('display', 'none');
					$('.main-answers .teacher-new-answer').css('display', 'none');
				}
			});
		},
		//追问回答 + 老师回复追问
		replyAnswer:function(){
			var isTeacher = cookie.getCookie('isTeacher');
			if (isTeacher == 1){
				var aType = 1;
			}
			else if (isTeacher == 0){
				var aType = 0;
			}
			$(document).on('click', '.answer-container .reply button', function(){
				var userId = cookie.getCookie('userId');
				if (userId != ''){
					var content = $(this).parent().find('input').val();
					var answerId = $(this).parents('.answer-container').attr('data-answerId');
					if (content == ''){
						alert('内容不能为空！');
						return ;
					}
					//改变按钮为不可选状态
					$(this).addClass('disabled');

					var request = $.ajax({
						url: config['api']['replyAnswer'][0].replace('<answer_id>', answerId),
						type: config['api']['replyAnswer'][1],
						data: {
							content: content,
							aType: aType
						},
						dataType: 'json',
						async: true,
						error: function(err){
							console.log('reply answer failed!');
							alert('追问失败，请重试！')
							$('.answer-container .reply button').removeClass('disabled');
						},
						success: function(data){
							alert('追问成功！');
							console.log(data)
							window.location.reload();
						}
					});
				}
				else{
					alert('请先登录！');
					$('#top_bar .user').css('display', 'none');
					$('#top_bar .log_reg').css('display', 'inline');	
					$('.user-info').css('display', 'none');
					$('.answer-container .reply').css('display', 'none');
					$('.main-answers .teacher-new-answer').css('display', 'none');
				}
			});
		},
		//问题详情页发表新评论
		newComment: function(){
			$(document).on('click', '.show-comments .normal-comment button', function(){
				var userId = cookie.getCookie('userId');

				if (userId != ''){
					var content = $(this).parent().find('textarea').val();
					var problemId = $(this).parents('.articles').attr('data-problemId');
					if (content == ''){
						alert('内容不能为空！');
						return ;
					}
					//改变按钮为不可选状态
					$(this).addClass('disabled');

					var request = $.ajax({
						url: config['api']['postComment'][0].replace('<user_id>', userId),
						type: config['api']['postComment'][1],
						data: {
							content: content,
							problemId: problemId
						},
						dataType: 'json',
						async: true,
						error: function(err){
							console.log('comment failed!');
							alert('评论失败，请重试！')
							$('.show-comments .normal-comment button').removeClass('disabled');
						},
						success: function(data){
							alert('评论发表成功！');
							window.location.reload();
						}
					});
				}
				else{
					alert('请先登录！');
					$('#top_bar .user').css('display', 'none');
					$('#top_bar .log_reg').css('display', 'inline');	
					$('.user-info').css('display', 'none');
					$('.answer-container .reply').css('display', 'none');
					$('.main-answers .teacher-new-answer').css('display', 'none');
				}
			});
		},
		//回复评论
		replyComment: function(){
			//对某条评论按回复
			$(document).on('click', '.main-comments .comment-right-col span', function(){
				var fromUser = $(this).parents('.comment-content').attr('data-fromUser');
				var fromUserName = $(this).parents('.comment-right-col').find('h5 a').text();
				$('.information .normal-comment').css('display', 'none');
				$('.information .reply').css('display', 'block');
				$('.information .reply').attr('data-replyTo', fromUser);
				$('.information .reply textarea').attr('placeholder', '回复 @'+fromUserName+' : ')
			});
			//按取消
			$(document).on('click', '.show-comments .reply .reply-cancel', function(){
				$('.information .reply').css('display', 'none');
				$('.information .normal-comment').css('display', 'block');
			});
			//提交回复
			$(document).on('click', '.show-comments .reply .reply-submit', function(){
				var userId = cookie.getCookie('userId');

				if (userId != ''){
					var content = $(this).parent().find('textarea').val();
					var problemId = $(this).parents('.articles').attr('data-problemId');
					var replyTo = $(this).parent().attr('data-replyTo');
					if (content == ''){
						alert('内容不能为空！');
						return ;
					}
					//改变按钮为不可选状态
					$(this).addClass('disabled');

					var request = $.ajax({
						url: config['api']['postComment'][0].replace('<user_id>', userId),
						type: config['api']['postComment'][1],
						data: {
							replyTo: replyTo,
							content: content,
							problemId: problemId
						},
						dataType: 'json',
						async: true,
						error: function(err){
							console.log('comment failed!');
							alert('评论失败，请重试！')
							$('.show-comments .reply button').removeClass('disabled');
						},
						success: function(data){
							alert('评论发表成功！');
							window.location.reload();
						}
					});
				}
				else{
					alert('请先登录！');
					$('#top_bar .user').css('display', 'none');
					$('#top_bar .log_reg').css('display', 'inline');	
					$('.user-info').css('display', 'none');
					$('.answer-container .reply').css('display', 'none');
					$('.main-answers .teacher-new-answer').css('display', 'none');
				}
			});	
		}
	};
});
